package com.junko.api.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.junko.core.tool.ToolDateTime;
import com.junko.core.tool.ToolPassword;
import com.junko.model.JsonResult;
import com.junko.model.app.User;
import com.junko.service.app.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/api/login")
@Api(value = "用户登录")
public class LoginCtrl extends BaseApiController{
    private Logger logger = LogManager.getLogger(LoginCtrl.class);

    @Resource
    private IUserService userService;

    @ApiOperation(httpMethod = "POST", value = "执行登录")
    @PostMapping
    public JsonResult login(
            @ApiParam(value = "用户名、手机号", required = true) @RequestParam String account,
            @ApiParam(value = "密码", required = true) @RequestParam String password) {
        try {
            //开发环境下
            User user = userService.findByAccount(account);
            if (user == null) {
                return fail("用户名或手机号不存在");
            }
            if (!ToolPassword.checkPassword(user.getSalt(),user.getPassword(),password)) {
                return JsonResult.fail("用户名/手机号 或 密码错误");
            }
            if (user.getLocked()) {
                return fail("该账号已被禁用");
            }
            Algorithm algorithm = Algorithm.HMAC256("secret");
            String token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("id", user.getId())
                    .withClaim("userName", user.getUserName())
                    //7天的有效时间
                    .withExpiresAt(ToolDateTime.getDateByPlusDays(new Date(), 7))
                    .sign(algorithm);
            return JsonResult.success((Object) token);
        } catch (Exception e) {
            logger.error("登录异常,e=", e);
            e.printStackTrace();
            return fail("登录失败,请重试");
        }
    }
}